package org.yjhking.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YJH
 */
@Component
public class LoginCheckFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }
    
    @Override
    public int filterOrder() {
        return 0;
    }
    
    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String requestURI = request.getRequestURI();
        // 返回true拦截并调用run()方法，false放行
        return !requestURI.endsWith("login") && !requestURI.endsWith("register");
    }
    
    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            try {
                PrintWriter writer = response.getWriter();
                Map<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("msg", "请先登录");
                String data = JSON.toJSONString(map);
                writer.write(data);
                // 阻止filter后续执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
